#!/usr/bin/env python
# -*- coding:utf-8 -*-
# file:do_file_score_input.py
# author:肖宇轩
# datetime:2024-11-12 20:27
# software: VsCode

"""
从键盘循环连续输入n个同学的姓名，语文，数学，外语成绩，保存到一个txt文件中；备注：程序测试时，n请赋值为3和5分别测试；
"""

import os


def input_grade(n):
    with open("grades.txt", "w") as file:
        for i in range(1, n + 1):
            data = input(f"请输入第{i}个同学的姓名及语数外成绩：")
            file.write(data + "\n")
            if i < n:
                print(f"请继续输入第{i + 1}个同学的成绩：")


def grade_sort():
    students = []


    with open("grades.txt", "r") as file:
        for line in file:

            data = line.strip().split()
            name = data[0]
            chinese = int(data[1])
            math = int(data[2])
            english = int(data[3])
            total_score = chinese + math + english

            students.append((name, chinese, math, english, total_score))


    students.sort(key=lambda x: (-x[4], -x[1], -x[2], -x[3]))


    with open("sorted_grades.txt", "w") as file:

        file.write("名次  姓名   语文  数学  英语  总分\n")
        file.write("-----------------------------------\n")

        for rank, student in enumerate(students, start=1):
            file.write(f"{rank:<4} {student[0]:<4} {student[1]:<4} {student[2]:<4} {student[3]:<4} {student[4]:<4}\n")

    print("成绩已保存到文件 sorted_grades.txt 中")

# 主程序
if __name__ == '__main__':
    n = 3
    input_grade(n)
    grade_sort()

